'use strict';
layui.define('jquery', function(exports){
	let $ = layui.jquery;


	//发送邮件
	let sendEmail = {
		url : '',
		btn : '',
		input : '',
		timer : null,
		flag: true,
		disabled:'',

		//初始化
		init : function(obj){
			this.btn   = $(obj.btn);
			this.input = $(obj.input);
			this.url   = obj.url;
			this.disabled   = obj.disabled;
			this.addEvent();
		},

		//添加事件
		addEvent : function(){
			let that = this;
			that.btn.on('click', function(){
				if(!that.flag) return;

				that.flag = false;


				let email = that.input.val();
				if( email.length <= 0 || that.btn.hasClass(that.disabled) ) return;

				//判断是否是有效邮箱
				if( !that.checkEmail(email) ){
					layer.msg('请输入有效邮箱地址.');
					return;
				}

				//防止重复点击
				that.btn.addClass(that.disabled);

				//发送邮件地址
				that.send(email);
			});
		},

		//发送请求
		send : function(email){
			let that = this;
			$.ajax({
				url : that.url,
				type : 'POST',
				data : {email : email},
				success : function(d){
					if(d.code === 0){
						//邮件发送成功
						that.setTimer();
					}else{
						//发送失败
						setTimeout(function(){
							that.btn.removeClass(that.disabled);
							that.flag = true;
						},3000);
						layer.msg(d.msg);

					}

				}
			});

		},
		//定时器
		setTimer: function(){
			clearInterval(this.timer);

			let second = 60;
			let that = this;

			//禁止点击按钮
			if( !this.btn.hasClass(that.disabled) ) this.btn.addClass(that.disabled);

			this.btn.text('已发送...');


			this.timer = setInterval(function(){
				second--;

				if(second <= 0){
					that.btn.text('发送验证码').removeClass(that.disabled);
					clearInterval(that.timer);
					that.flag = true;
				}else{
					that.btn.text(' - ' + second + ' - ');
				}
			},1000);
		},

		//检测是否是有效邮箱
		checkEmail : function(email){
			let reg = /^\w{5,15}@[a-z0-9]+(\.[a-z]+)+$/;
			return email.match(reg) !== null;
		}
	};
  
	//输出test接口
	exports('email', sendEmail);
}); 